﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Example.Base.Interfaces.Services;
using Example.Base.Entities;
using Example.Base.Interfaces.Repositories;
using Example.Base.Interfaces.Validators;
using Example.Base.Interfaces.Services.DataServices;
using Example.Base.EventArgs;
using System.Threading.Tasks;
using System.Threading;
using RestSharp;
using System.Xml.Linq;
using System.Xml;
using System.Text.RegularExpressions;

namespace Example.Data.Services.DataServices
{
    public class WeatherService: IDataService<Region>
    {
        #region Get Weather        
        public Task<Region> AsyncGet()
        {
            return Task.Factory.StartNew<Region>(privateAsyncGet);
        }        

        private Region privateAsyncGet()
        {
            var client = new RestClient();
            client.BaseUrl = "http://rp5.ru";                       

            var request = new RestRequest();
            request.Resource = "xml/6601/00000/en";            

            var response = client.Execute(request);

            var xml = XElement.Parse(response.Content);

            var region = new Region
            {
                Name = xml.Element("point").Element("point_name").Value
            };

            var weather = xml
                .Element("point")
                .Elements("timestep")
                .Select(x => new Weather
                    {
                        Date = DateTime.Parse(x.Element("datetime").Value).ToString("d"),
                        Time = DateTime.Parse(x.Element("datetime").Value).ToString("t"),
                        Temperature = Int16.Parse(x.Element("temperature").Value),
                        Pressure = Int16.Parse(x.Element("pressure").Value),
                        Humidity = Int16.Parse(x.Element("humidity").Value)
                    });

            region.Prognose = weather;

            return region;
        }
        #endregion             
    }
}
